<template>
  <div :class="$style.printPage">
    <table class="print-layout">
      <thead>
        <tr>
          <th>
            <slot name="header"></slot>
          </th>
        </tr>
      </thead>
      <tbody>
        <tr>
          <td>
            <slot></slot>
          </td>
        </tr>
      </tbody>
      <tfoot>
        <tr>
          <td class="footer">
            <div class="clearfix">
              <slot name="footer"></slot>
            </div>
          </td>
        </tr>
      </tfoot>
    </table>
    <!-- 解决最后一页位置的问题 -->
    <footer class="clearfix">
      <slot name="footer"></slot>
      <span :class="$style.pageCounter"></span>
    </footer>
  </div>
</template>

<script lang="ts">
  import { Component, Vue, Prop } from "@some21/vue-class-decorator";

  @Component({
    name: "PrintPage",
  })
  export default class extends Vue {
    @Prop({ type: String, required: true, default: "A4" })
    page: string;

    mounted() {}
    beforeDestroy() {
      this.$el.remove();
    }
    print() {
      const printNode = this.$el.cloneNode(true);
      // 克隆一个组件出来
      document.body.appendChild(printNode);
      this.$nextTick(() => {
        window.print();
        // 移除组件
        document.body.removeChild(printNode);
      });
    }
  }
</script>

<style lang="scss" module>
  // 设定默认打印参数
  @page {
    margin: 3.5mm; // 默认页边距
    size: A4 portrait; // 默认纸张 方向。横向：landscape；纵向：portrait
    font-size: 10.5pt; // 打印默认字体
    border: none;
    font-family: "YaHei", "宋体", "Arial Narrow", Arial, sans-serif;
    background: #fff;
    color: #fff;
    -webkit-font-smoothing: initial;
    -webkit-text-stroke-width: initial;
    -moz-osx-font-smoothing: initial;
    text-rendering: initial;
  }
  @media media {
    :global(body) > .print-page {
      display: none;
    }
  }
  .print-page {
    font-size: 13pt;
    padding: 3.5mm;
    position: relative;
    background: #fff;
    box-sizing: border-box;
    //自动分页选项
    page-break-before: auto;
    page-break-after: always;

    > :global(footer) {
      bottom: 0;
      position: fixed;
      width: 100%;
      display: none;
      overflow: hidden;
    }
  }

  @media print {
    .page-counter:first-child {
      counter-reset: page;
    }
    :global(body) > :not(.print-page) {
      display: none;
    }
    .print-page {
      background: #fff;
      margin: 0;
      orphans: 0;
      widows: 0;
      padding: 0;
      width: 100% !important;

      > :global(footer) {
        display: block;
      }
      > :global(.print-layout tfoot .footer) {
        visibility: hidden;
      }
    }
  }
</style>
